package com.suray.wcs.web.system.controller;

import com.suray.basic.wcs.path.core.Node;
import com.suray.basic.wcs.path.enums.NodeStatus;
import com.suray.basic.wcs.path.enums.NodeType;
import com.suray.basic.wcs.plc.core.Plc;
import com.suray.basic.wcs.plc.entity.PlcDeviceDB;
import com.suray.basic.wcs.plc.enums.PlcDeviceType;
import com.suray.basic.wcs.plc.pojo.oper.lifter.LifterOper;
import com.suray.basic.wcs.plc.pojo.oper.StationOper;
import com.suray.basic.wcs.plc.pojo.oper.lifter.TwoDirectionRgvLifterOper;
import com.suray.basic.wcs.plc.pojo.oper.single.DeviceInterface;
import com.suray.basic.wcs.plc.pojo.oper.single.TransPlanter;
import com.suray.basic.wcs.plc.service.impl.PlcDeviceDBServiceImpl;
import com.suray.basic.wcs.plc.utils.PlcDeviceProcess;
import com.suray.basic.wcs.plc.utils.PlcTaskType;
import com.suray.basic.wcs.plc.utils.PlcUnit;
import com.suray.basic.wcs.utils.LoggerUtil;
import com.suray.basic.wcs.utils.WcsFuncUtil;
import com.suray.commin.annotation.Log;
import com.suray.commin.core.controller.BaseController;
import com.suray.commin.core.controller.ResponseData;
import com.suray.commin.core.page.TableDataInfo;
import com.suray.commin.core.utils.ExcelUtil;
import com.suray.commin.enmus.BusinessType;
import com.suray.system.run.random.code.LadderNavigate;
import com.suray.wcs.res.enums.PalletStatus;
import com.suray.wcs.res.enums.RgvStatus;
import com.suray.wcs.res.enums.RgvType;
import com.suray.wcs.service.config.properties.WcsProperties;
import com.suray.wcs.service.core.path.api.RgvTaskAssign;
import com.suray.wcs.service.core.path.api.impl.RgvSonNewTaskHandle;
import com.suray.wcs.service.core.util.CommonUtil;
import com.suray.wcs.service.core.util.DateUtil;
import com.suray.wcs.service.enums.*;
import com.suray.wcs.service.init.SystemInit;
import com.suray.wcs.service.plc.LifterPathNode;
import com.suray.wcs.service.pojo.*;
import com.suray.wcs.service.system.bo.ConnectNodeBO;
import com.suray.wcs.service.system.bo.NodeAndPlanBO;
import com.suray.wcs.service.system.entity.*;
import com.suray.wcs.service.system.service.impl.*;
import com.suray.wcs.service.test.action.ActionCycleTask;
import com.suray.wcs.service.test.action.TaskCycleAction;
import com.suray.wcs.service.test.action.checkmap.RgvCheckMap;
import com.suray.wcs.service.test.type.ActionTestType;
import com.suray.wcs.service.thread.PlcTaskThread;
import com.suray.wcs.service.util.WcsUtil;
import com.suray.wcs.service.wmsconnect.TaskApply;
import com.suray.wcs.service.wmsconnect.TaskStatusRtn;
import com.suray.wcs.service.wmsconnect.ToWms;
import com.suray.wcs.web.system.request.ChangeTaskInfoRequest;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 任务管理前端控制器
 *
 * @author Administrator
 */
@RestController
@RequestMapping("/taskdb")
@CrossOrigin
public class TaskDBController extends BaseController {
    @Autowired
    private RgvTaskAssign rgvTaskAssign;
    @Autowired
    private NodeDBServiceImpl nodeDBService;
    @Autowired
    private TaskDBServiceImpl taskDBService;
    @Autowired
    private TaskDetailServiceImpl taskDetailService;
    @Autowired
    private ProgrammeServiceImpl portConfServiceImpl;
    @Autowired
    private PlcDeviceDBServiceImpl plcdevicedbServiceImpl;
    @Autowired
    private RgvDBServiceImpl rgvDBService;
    @Autowired
    private PortDBServiceImpl portService;
    @Autowired
    private ToWms toWms;
    @Autowired
    private WareHouseDBServiceImpl wareHouseDBService;
    @Autowired
    private PlcDeviceDBServiceImpl plcDeviceDBService;
    @Autowired
    private ConnectConfServiceImpl connectConfService;

    private Logger log = LoggerFactory.getLogger(this.getClass());
    private String errColor = "#FE3838";
    private String warnColor = "#FF9900";
    private String normalColor = "#999999";

    /**
     * 入库申请
     */
    @PreAuthorize("@ss.hasPermi('taskdb:applyIn')")
    @Log(title = "任务管理", method = "入库申请", businessType = BusinessType.INSERT)
    @PostMapping(value = "/applyIn")
    @ResponseBody
    @ApiOperation(value = "入库申请")
    public ResponseData applyIn(@RequestBody TaskApply taskApply) {
        if (taskApply == null) {
            return ResponseData.error("入库申请不能为空");
        }
        if (taskApply.getBarCode() == null && StringUtils.isEmpty(taskApply.getBarCode())) {
            return ResponseData.error("托盘码不能为空");
        }
        if (taskApply.getFromPort() == null && StringUtils.isEmpty(taskApply.getFromPort())) {
            return ResponseData.error("入库口不能为空");
        }
        taskApply.setApplyTime(DateUtil.format(new Date(), DateUtil.YMDHMS));
        if (toWms.exeTaskApply(taskApply).getReturnStatus() == WcsProperties.SUCCESS) {
            return ResponseData.success(taskApply + "的入库申请发送成功");
        }
        return ResponseData.error("入库申请失败！！！");
    }

    @PreAuthorize("@ss.hasPermi('taskdb:generate')")
    @Log(title = "任务管理", method = "任务生成", businessType = BusinessType.INSERT)
    @PostMapping(value = "/generateTask")
    @ResponseBody
    @ApiOperation(value = "任务生成")
    public ResponseData generateTask(@RequestBody TaskGenerateRequest taskGenerate) {
        try {
            TaskDB taskdb = new TaskDB();
            if (taskGenerate == null) {
                return ResponseData.error("任务不能为空");
            }
            if (taskGenerate.getTaskType() == null) {
                return ResponseData.error("任务类型不能为空");
            }
            if (taskGenerate.getTaskType() == TaskType.IN.getTypeNum() && StringUtils.isEmpty(taskGenerate.getStartNodeStr())) {
                return ResponseData.error("入库任务，请选择入库口");
            }
            if (taskGenerate.getTaskType() == TaskType.IN.getTypeNum() && StringUtils.isEmpty(taskGenerate.getEndNodeStr())) {
                return ResponseData.error("入库任务，请设置终点");
            }
            if (taskGenerate.getTaskType() == TaskType.OUT.getTypeNum() && StringUtils.isEmpty(taskGenerate.getStartNodeStr())) {
                return ResponseData.error("出库任务，请设置起点");
            }
            if (taskGenerate.getTaskType() == TaskType.OUT.getTypeNum() && StringUtils.isEmpty(taskGenerate.getEndNodeStr())) {
                return ResponseData.error("出库任务，请选择出库口");
            }
            if (taskGenerate.getTaskType() == TaskType.TRANSFER.getTypeNum() && StringUtils.isEmpty(taskGenerate.getStartNodeStr())) {
                return ResponseData.error("移库任务，请设置起点");
            }
            if (taskGenerate.getTaskType() == TaskType.TRANSFER.getTypeNum() && StringUtils.isEmpty(taskGenerate.getEndNodeStr())) {
                return ResponseData.error("移库任务，请设置终点");
            }
            if (taskGenerate.getTaskType() == TaskType.MOVE_LOADED.getTypeNum() && StringUtils.isEmpty(taskGenerate.getEndNodeStr())) {
                return ResponseData.error("载货行驶，请设置终点");
            }
            if (taskGenerate.getTaskType() == TaskType.MOVE_UNLOADED.getTypeNum() && StringUtils.isEmpty(taskGenerate.getEndNodeStr())) {
                return ResponseData.error("空载行驶，请设置终点");
            }
            if (taskGenerate.getTaskType() == TaskType.MOVE_LOADED.getTypeNum() && taskGenerate.getRgvNo() == null) {
                return ResponseData.error("该任务类型不支持系统分配执行车辆！请手动分配小车");
            }
            if (taskGenerate.getTaskType() == TaskType.MOVE_UNLOADED.getTypeNum() && taskGenerate.getRgvNo() == null) {
                return ResponseData.error("该任务类型不支持系统分配执行车辆！请手动分配小车");
            }
            if (taskGenerate.getTaskType() == TaskType.CHARGE.getTypeNum() && taskGenerate.getRgvNo() == null) {
                return ResponseData.error("该任务类型不支持系统分配执行车辆！请手动分配小车");
            }
            String status = null;
            //出入库 联机不可下发任务
            if (taskGenerate.getTaskType() == TaskType.IN.getTypeNum() || taskGenerate.getTaskType() == TaskType.OUT.getTypeNum() ) {
                //查询当前库区对象
                WareHouseDB wareHousePojo = wareHouseDBService.getCurWareHouseDB();
                status = wareHousePojo.getStatus();
                if (status.equals("0")) {
                    return ResponseData.error("现在是联机模式，不可手动下发出库和移库任务");
                }
            }
            Rgv rgv = null;
            RgvDB rgvdb = null;
            if (!taskGenerate.isSystemAssignedMode()) {
                rgv = SystemInit.getByRgvNo(taskGenerate.getRgvNo());
                if (taskGenerate.getTaskType() == TaskType.RUN_FOR_GCODE.getTypeNum()) {
                    if (rgv.checkRgvType(RgvType.RGV_SEER_COMM)) {
                        return ResponseData.error(rgv.getRgvName() + "不支持乱序跑码任务!");
                    }
                    generalRunForGCode(taskGenerate.getStartNodeStr(), taskGenerate.getEndNodeStr(),
                            taskGenerate.getRgvNo());
                    return ResponseData.success("乱序跑码任务生成成功");
                }
                if (taskGenerate.getRgvNo() == null) {
                    return ResponseData.error("该任务类型不支持系统分配执行车辆！请手动分配小车");
                }

                if (RgvStatus.OFF_LINE == rgv.getRgvStatus()) {
                    return ResponseData.error("设置小车已离线");
                }
                if (rgv.getCurLocation() == null) {
                    if (rgv.checkRgvType(RgvType.RGV_SEER_COMM)) {
                        return ResponseData.error("请确认是否有控制权且 定位正确");
                    } else {
                        return ResponseData.error("请设置小车位置");
                    }
                }
                if (!rgv.checkRgvType(RgvType.RGV_FORK)) {
                    if (PalletStatus.UP == rgv.getPalletStatus()) {
                        if (taskGenerate.getTaskType() == TaskType.MOVE_UNLOADED.getTypeNum()
                                || taskGenerate.getTaskType() == TaskType.CHARGE.getTypeNum()) {
                            return ResponseData.error("当前任务不可在托板顶升时执行，请确认小车托板是否顶升");
                        }
                    }
                }
                rgvdb = rgvDBService.getRgvDBByNo(taskGenerate.getRgvNo());
                if (taskGenerate.getTaskType() == TaskType.CHARGE.getTypeNum()) {
                    if (StringUtils.isEmpty(rgvdb.getChargeLocation()) && StringUtils.isEmpty(taskGenerate.getEndNodeStr())) {
                        return ResponseData.error("请先设置或选择小车的充电位");
                    }
                    if (StringUtils.isEmpty(rgvdb.getChargeLocation())) {
                        Node node = Node.parseGrid(taskGenerate.getEndNodeStr());
                        NodeDB nodeDB = nodeDBService.getNodeDB(node);
                        if (nodeDB.getGridType().getCodeNum().intValue() != NodeType.C.getCodeNum().intValue()) {
                            return ResponseData.error("选择的终点不是充电位");
                        }
                    } else {
                        if (!StringUtils.isEmpty(taskGenerate.getEndNodeStr())) {
                            return ResponseData.error("小车已设置充电位，请不要选择终点。");
                        }
                    }
                }
            }
            ConnectNodeBO startPlanBO = null;
            ConnectNodeBO endPlanBO = null;

            NodeDB rgvStartSNode = getRgvStartNode(taskGenerate);
            Node startNode = parseNodedb(rgvStartSNode);

            if (!StringUtils.isEmpty(startNode)) {
                NodeDB nodedb = nodeDBService.getNodeDB(startNode);
                if (nodedb != null && nodedb.getGridType().getCode().equals(NodeType.B.getCode())) {
                    return ResponseData.error("起点位置禁用，不能生成任务");
                }
                if (nodedb != null && !nodedb.getCanToStop()) {
                    return ResponseData.error("起点位置不可停留，不能生成任务");
                }
            }
            Node endNode;
            NodeDB rgvEndSNode = null;
            if (TaskType.CHARGE.getTypeNum() == taskGenerate.getTaskType()) {
                if (!StringUtils.isEmpty(rgvdb.getChargeLocation())) {
                    endNode = Node.parseGrid(rgvdb.getChargeLocation());
                } else {
                    endNode = Node.parseGrid(taskGenerate.getEndNodeStr());
                }
            } else {
                rgvEndSNode = getRgvEndNode(taskGenerate);
                endNode = parseNodedb(rgvEndSNode);
            }

            if (rgvEndSNode != null && rgvEndSNode.getGridType().getCode().equals(NodeType.B.getCode())) {
                return ResponseData.error("终点位置禁用，不能生成任务");
            }
            if (rgvEndSNode != null && !rgvEndSNode.getCanToStop()) {
                return ResponseData.error("终点位置不可停留，不能生成任务");
            }
            if (rgvEndSNode != null && taskGenerate.getTaskType() == TaskType.TRANSFER.getTypeNum()
                    && rgvEndSNode.getGridStatus().equals(NodeStatus.Y.toString()) && NodeType.P.equals(rgvEndSNode.getGridType())) {
                return ResponseData.error("移库任务，终点有货");
            }
            if (rgvEndSNode != null && taskGenerate.getTaskType() == TaskType.IN.getTypeNum()
                    && rgvEndSNode.getGridStatus().equals(NodeStatus.Y.toString())) {
                return ResponseData.error("入库任务，终点有货");
            }

            // 入库起点为空，未找到最适合的入库方案起点，则寻找接驳配置
            if(taskGenerate.getTaskType() == TaskType.IN.getTypeNum() && startNode == null){
                if(rgvEndSNode == null){
                    return ResponseData.error("入库任务，终点不存在");
                }
                startPlanBO = getConnectNodePlan(taskGenerate.getStartNodeStr(), taskGenerate.getEndNodeStr(), null, rgvEndSNode, TaskType.IN.getTypeNum());

                if(startPlanBO == null){
                    return ResponseData.error("入库任务，找不到匹配的入库方案和接驳方案");
                }
                startNode = parseNodedb(startPlanBO.getNodedb());
            }

            // 出库终点为空，未找到最适合的出库方案终点，则寻找接驳配置
            if(taskGenerate.getTaskType() == TaskType.OUT.getTypeNum() && endNode == null){
                if(startNode == null){
                    return ResponseData.error("出库任务，起点不存在");
                }
                endPlanBO = getConnectNodePlan(taskGenerate.getStartNodeStr(), taskGenerate.getEndNodeStr(), rgvStartSNode, null, TaskType.OUT.getTypeNum());

                if(endPlanBO == null){
                    return ResponseData.error("出库任务，找不到匹配的出库方案和接驳方案");
                }
                endNode = parseNodedb(endPlanBO.getNodedb());
            }

            // 移库任务起点和终点不同层，则判断是否接驳
            if(taskGenerate.getTaskType() == TaskType.TRANSFER.getTypeNum() && startNode.getZ() != endNode.getZ()){
                endPlanBO = getConnectNodePlan(taskGenerate.getStartNodeStr(), taskGenerate.getEndNodeStr(), rgvStartSNode, rgvEndSNode, TaskType.TRANSFER.getTypeNum());
            }

            if(startPlanBO != null){
                taskdb.setPreConnect(startPlanBO.getPreConnect());
                taskdb.setSufConnect(startPlanBO.getSufNodeConnect());
                taskdb.setConnectPortCode(startPlanBO.getConnectPortCode());
            } else if(endPlanBO != null){
                taskdb.setPreConnect(endPlanBO.getPreConnect());
                taskdb.setSufConnect(endPlanBO.getSufNodeConnect());
                taskdb.setConnectPortCode(endPlanBO.getConnectPortCode());
            }

            Rgv assignedRgv = taskGenerate.isSystemAssignedMode() ? null : rgv;
            taskdb.setStartNode(startNode);
            taskdb.setEndNode(endNode);
            if (taskGenerate.getTaskType() == TaskType.OUT.getTypeNum() || taskGenerate.getTaskType() == TaskType.TRANSFER.getTypeNum()) {
                NodeDB starNodeDB = nodeDBService.getNodeDB(taskdb.selectStartNode());
                taskdb.setBarCode(starNodeDB.getPalletCode());
            }
            taskdb.setTaskType(TaskType.parseTaskType(taskGenerate.getTaskType()));
            if (taskGenerate.getTaskType() == TaskType.IN.getTypeNum()) {
                taskdb.setTaskPortId(taskGenerate.getStartNodeStr());
            } else if (taskGenerate.getTaskType() == TaskType.OUT.getTypeNum()) {
                taskdb.setTaskPortId(taskGenerate.getEndNodeStr());
            }
            taskdb.setProcessingRgvNo(assignedRgv == null ? null : assignedRgv.getRgvDB().getRgvNo());
            taskdb.setPreProcessingRgvNo(assignedRgv == null ? null : assignedRgv.getRgvDB().getRgvNo());
            taskdb.setPriorityCode(CommonUtil.PRIORITY_CODE_MANUAL);
            if(taskdb.getPreConnect() != null && taskdb.getSufConnect() != null){
                splitTask(taskdb);
            } else {
                taskDBService.insertTask(Collections.singletonList(taskdb));
            }

            return ResponseData.success("任务生成成功", taskdb);
        } catch (Exception e) {
            WcsFuncUtil.exceptionLog(e, this.getClass());
            return ResponseData.error("任务生成失败：" + e.getMessage());
        }
    }

    private void generalRunForGCode(String startNodeStr, String endNodeStr, Integer rgvNo) {
        if (StringUtils.isEmpty(startNodeStr)) {
            throw new RuntimeException("请选择起点");
        }

        if (StringUtils.isEmpty(endNodeStr)) {
            throw new RuntimeException("请选择终点");
        }

        if (rgvNo == null) {
            throw new RuntimeException("请选择进行跑码的小车");
        }

        Node startNode = Node.parseGrid(startNodeStr);
        Node endNode = Node.parseGrid(endNodeStr);
        Rgv rgv = SystemInit.getByRgvNo(rgvNo);

        if (startNode.getZ() != endNode.getZ()) {
            throw new RuntimeException("两点不在同一层，不能进行乱序跑码");
        } else if (startNode.equals(endNode)) {
            throw new RuntimeException("不能选两个相同的点进行跑码任务");
        }

        if (rgv.getRgvStatus() == RgvStatus.OFF_LINE) {
            throw new RuntimeException("小车离线");
        }

        if (rgv.getCurLocation() == null) {
            throw new RuntimeException("请同步小车");
        }

        int rgvDir = wareHouseDBService.getCurWareHouseDB().getMapDirection();

        //小车1,3方向为巷道方向
        new LadderNavigate(rgv, startNode, endNode, (rgvDir == 1 || rgvDir == 3)).navigate();
    }

    /**
     * 接驳任务
     * @param taskDB
     */
    private void splitTask(TaskDB taskDB){
        TaskDB preTask = new TaskDB();
        preTask.setStartNode(taskDB.selectStartNode());
        preTask.setEndNode(taskDB.getPreConnect());
        if(TaskType.TRANSFER.equals(taskDB.getTaskType())){
            preTask.setTaskType(TaskType.OUT);
        } else {
            preTask.setTaskType(taskDB.getTaskType());
        }
        if(TaskType.IN.equals(preTask.getTaskType())){
            preTask.setTaskPortId(taskDB.getTaskPortId());
        } else {
            preTask.setTaskPortId(taskDB.getConnectPortCode());
        }

        preTask.setPriorityCode(taskDB.getPriorityCode());
        preTask.setBarCode(taskDB.getBarCode());
        preTask.setWmsTaskId(null);

        taskDBService.insertTask(Collections.singletonList(preTask));

        TaskDB sufTask = new TaskDB();
        sufTask.setStartNode(taskDB.getSufConnect());
        sufTask.setEndNode(taskDB.selectEndNode());
        if(TaskType.OUT.equals(taskDB.getTaskType())){
            sufTask.setTaskPortId(taskDB.getTaskPortId());
        } else {
            sufTask.setTaskPortId(taskDB.getConnectPortCode());
        }
        sufTask.setTaskType(taskDB.getTaskType());
        sufTask.setPriorityCode(taskDB.getPriorityCode());
        sufTask.setBarCode(taskDB.getBarCode());
        sufTask.setWmsTaskId(taskDB.getWmsTaskId());
        sufTask.setPreTaskId(preTask.getTaskId());

        taskDBService.insertTask(Collections.singletonList(sufTask));
    }

    /**
     * 根据WMS发送的任务获取最优的接驳配置
     */
    private ConnectNodeBO getConnectNodePlan(String startStr, String endStr, NodeDB start, NodeDB end, Integer taskType) {
        // 接驳点方案集合
        List<ConnectConfDB> connectDBList;
        ConnectNodeBO connectNodeBO = null;

        if (taskType.equals(TaskType.IN.getTypeNum())) {
            Node node = new Node(end.getGridx(), end.getGridy(), end.getGridz());
            connectDBList = connectConfService.findByType(PortModel.IN_PORT.getValue());
            // 最适合的入库接驳配置方案
            connectNodeBO = nodeDBService.getMostConnectNodeAndPlan(startStr, node.toString(),
                    TaskType.parseTaskType(taskType), connectDBList);
        } else if(taskType.equals(TaskType.OUT.getTypeNum())){
            Node node = new Node(start.getGridx(), start.getGridy(), start.getGridz());
            connectDBList = connectConfService.findByType(PortModel.OUT_PORT.getValue());
            // 最适合的出库接驳配置方案
            connectNodeBO = nodeDBService.getMostConnectNodeAndPlan(node.toString(), endStr,
                    TaskType.parseTaskType(taskType), connectDBList);
        } else if(taskType.equals(TaskType.TRANSFER.getTypeNum())){
            Node starNode = new Node(start.getGridx(), start.getGridy(), start.getGridz());
            Node endNode = new Node(end.getGridx(), end.getGridy(), end.getGridz());

            connectDBList = connectConfService.findByType(PortModel.TRANSFER_PORT.getValue());
            connectNodeBO = nodeDBService.getMostConnectNodeAndPlan(starNode.toString(), endNode.toString(),
                    TaskType.parseTaskType(taskType), connectDBList);
        }
        return connectNodeBO;
    }

    @Log(title = "任务管理", method = "输送线运行", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/stationRunTask")
    @ResponseBody
    @ApiOperation("输送线运行")
    public ResponseData stationRun(@RequestBody TaskGenerateRequest taskGenerate) {
        try {
            if (taskGenerate.getStartNodeStr() == null || "".equals(taskGenerate.getStartNodeStr())) {
                return ResponseData.error("工位行驶任务，请设置起点");
            }
            if (taskGenerate.getEndNodeStr() == null || "".equals(taskGenerate.getEndNodeStr())) {
                return ResponseData.error("工位行驶任务，请设置终点");
            }

            Node start = Node.parseGrid(taskGenerate.getStartNodeStr());
            Node end = Node.parseGrid(taskGenerate.getEndNodeStr());
            if (!nodeDBService.getNodeDB(start).getGridType().equals(NodeType.ST) &&
                    !nodeDBService.getNodeDB(start).getGridType().equals(NodeType.CONNECTION)) {
                return ResponseData.error("工位行驶任务，起点任务类型不匹配");
            }
            if (!nodeDBService.getNodeDB(end).getGridType().equals(NodeType.ST) &&
                    !nodeDBService.getNodeDB(end).getGridType().equals(NodeType.CONNECTION)) {
                return ResponseData.error("工位行驶任务，终点任务类型不匹配");
            }
            taskDBService.runStation(start, end, taskGenerate.getStationType() == null ?
                    null : PlcTaskType.parseValue(taskGenerate.getStationType()));
            return ResponseData.success("执行成功", null);
        } catch (Exception e) {
            WcsFuncUtil.exceptionLog(e, this.getClass());
            return ResponseData.error("执行失败:" + e.getMessage());
        }
    }

    /**
     * 根据库口名称找到最合适的小车任务起始点
     */
    private NodeDB getRgvStartNode(TaskGenerateRequest taskGenerate) {
        if (taskGenerate.getTaskType().equals(TaskType.IN.getTypeNum())) {
            NodeAndPlanBO nodeAndPlanBO = nodeDBService.getMostAccessibleNodeAndPlan(taskGenerate.getStartNodeStr(), taskGenerate.getEndNodeStr(),
                    TaskType.parseTaskType(taskGenerate.getTaskType()));
            return nodeAndPlanBO != null ? nodeAndPlanBO.getNodedb() : null;
        } else if (TaskType.OUT.getTypeNum() == taskGenerate.getTaskType()
                || TaskType.TRANSFER.getTypeNum() == taskGenerate.getTaskType()) {
            NodeDB nodedb = nodeDBService.getNodeDBByGridID(taskGenerate.getStartNodeStr());
            if (nodedb != null) {
                return nodedb;
            } else {
                return nodeDBService.getNodeDB(Node.parseGrid(taskGenerate.getStartNodeStr()));
            }
        }
        return null;
    }

    /**
     * 根据库口名称找到最合适的小车任务终点
     */
    private NodeDB getRgvEndNode(TaskGenerateRequest taskGenerate) {
        if (taskGenerate.getTaskType().equals(TaskType.OUT.getTypeNum())) {
            NodeAndPlanBO nodeAndPlanBO = nodeDBService.getMostAccessibleNodeAndPlan(taskGenerate.getStartNodeStr(), taskGenerate.getEndNodeStr(),
                    TaskType.parseTaskType(taskGenerate.getTaskType()));
            return nodeAndPlanBO != null ? nodeAndPlanBO.getNodedb() : null;
        } else {
            NodeDB nodedb = nodeDBService.getNodeDBByGridID(taskGenerate.getEndNodeStr());
            if (nodedb != null) {
                return nodedb;
            } else {
                return nodeDBService.getNodeDB(Node.parseGrid(taskGenerate.getEndNodeStr()));
            }
        }
    }

    @PreAuthorize("@ss.hasPermi('taskdb:queryTasks')")
    @GetMapping(value = "/queryTasks")
    @ApiOperation("查询任务列表")
    public TableDataInfo queryTasks(TaskDB taskDB) {
        startPage();
        List<TaskDB> pageResultBO = taskDBService.queryTasks(taskDB);
        Calendar before8 = Calendar.getInstance();
        before8.add(Calendar.MINUTE, -8);
        Date before8D = before8.getTime();

        Calendar before5 = Calendar.getInstance();
        before5.add(Calendar.MINUTE, -5);
        Date before5D = before5.getTime();
        if (pageResultBO.size() > 0) {
            for (TaskDB tempTaskDB : pageResultBO) {
                if (tempTaskDB.getTaskStatus().getProgressNum() < TaskStatus.FINISH.getProgressNum()
                        || tempTaskDB.getTaskStatus().getProgressNum() == TaskStatus.ERROR.getProgressNum()) {
                    setTaskColor(before8D, before5D, tempTaskDB);
                } else {
                    tempTaskDB.setColor(normalColor);
                }
                setPlcStatus(tempTaskDB);
            }
        }
        return getDataTable(pageResultBO);
    }

    /**
     * 设置任务PLC状态
     * @param tempTaskDB
     */
    private void setPlcStatus(TaskDB tempTaskDB) {
        if (tempTaskDB.getPlcProgress() == TaskPlcProgress.WAIT.getProgressNum()) {
            tempTaskDB.setPlcProgressStr("等待");
            return;
        }
        if (tempTaskDB.getPlcProgress() == TaskPlcProgress.ALL_DEVICE_COMPLETE.getProgressNum()) {
            tempTaskDB.setPlcProgressStr("所有设备任务完成（除小车）");
            return;
        }
        PlcDeviceDB plcdevicedb = plcdevicedbServiceImpl.queryPlcdevByDeviceId(tempTaskDB.getPlcProgress());
        if (plcdevicedb != null) {
            tempTaskDB.setPlcProgressStr(plcdevicedb.getDeviceName());
        }
    }

    /**
     * 根据任务执行时间设置任务颜色
     * @param before8D
     * @param before5D
     * @param tempTaskDB
     */
    private void setTaskColor(Date before8D, Date before5D, TaskDB tempTaskDB) {
        if ((tempTaskDB.getTaskStatus() != null && tempTaskDB.getTaskStatus() == TaskStatus.ERROR)
                || before8D.compareTo(tempTaskDB.getUpdateTime()) == 1) {
            tempTaskDB.setColor(errColor);
        } else if (before5D.compareTo(tempTaskDB.getUpdateTime()) == 1) {
            tempTaskDB.setColor(warnColor);
        } else {
            tempTaskDB.setColor(normalColor);
        }
    }

    @PreAuthorize("@ss.hasPermi('taskdb:queryTasks')")
    @GetMapping(value = "/findErrorTask/{rgvNo}")
    @ApiOperation("查询错误任务列表")
    public TableDataInfo queryErrorTasks(@PathVariable("rgvNo") Integer rgvNo) {
        startPage();
        List<TaskDB> pageResultBO = taskDBService.queryErrorTasksByRgvNo(rgvNo);
        Calendar before8 = Calendar.getInstance();
        before8.add(Calendar.MINUTE, -8);
        Date before8D = before8.getTime();

        Calendar before5 = Calendar.getInstance();
        before5.add(Calendar.MINUTE, -5);
        Date before5D = before5.getTime();
        if (pageResultBO.size() > 0) {
            for (TaskDB tempTaskDB : pageResultBO) {
                if (tempTaskDB.getTaskStatus().getProgressNum() != TaskStatus.FINISH.getProgressNum()
                        || tempTaskDB.getTaskStatus().getProgressNum() == TaskStatus.ERROR.getProgressNum()) {
                    setTaskColor(before8D, before5D, tempTaskDB);
                } else {
                    tempTaskDB.setColor(normalColor);
                }
                setPlcStatus(tempTaskDB);
            }
        }
        return getDataTable(pageResultBO);
    }

    @GetMapping("/queryPlcProgress/{id}")
    @ApiOperation("查询PLC任务状态枚举")
    public ResponseData queryPlcProgress(@PathVariable("id") Integer id) {
        if (id == null || id < 1) {
            return ResponseData.error("任务不存在");
        }
        TaskDB taskDB = taskDBService.queryTaskInfoById(id);
        List<BaseEum> progressList = new ArrayList<BaseEum>();
        progressList.add(new BaseEum(TaskPlcProgress.WAIT.getProgressNum(), "等待"));
        if (taskDB.getTaskProgrammeGridId() != null) {
            ProgrammeDB programmeDB = portConfServiceImpl.getById(taskDB.getTaskProgrammeGridId());
            if (programmeDB != null && programmeDB.getProgramme() != null) {
                String[] proGrammeArray = programmeDB.getProgramme().split("-");
                for (String item : proGrammeArray) {
                    if (String.valueOf(PlcDeviceProcess.CALL_RGV.getId()).equals(item)) {
                        continue;
                    } else if (
                            String.valueOf(PlcDeviceProcess.LOCK_HAVE_CARGO.getId()).equals(item)
                                    || String.valueOf(PlcDeviceProcess.LOCK_NO_CARGO.getId()).equals(item)
                                    || String.valueOf(PlcDeviceProcess.UNLOCK.getId()).equals(item)
                                    || String.valueOf(PlcDeviceProcess.FORWARD_TRANS_CARGO.getId()).equals(item)
                                    || String.valueOf(PlcDeviceProcess.BACK_TRANS_CARGO.getId()).equals(item)
                                    || String.valueOf(PlcDeviceProcess.TRANS_PLANTER_UP.getId()).equals(item)
                                    || String.valueOf(PlcDeviceProcess.TRANS_PLANTER_DOWN.getId()).equals(item)
                    ) {
                        PlcDeviceProcess deviceProcess = PlcDeviceProcess.parseDeviceProcess(Integer.valueOf(item));
                        progressList.add(new BaseEum(deviceProcess.getId(), deviceProcess.getDes()));
                        continue;
                    }
                    PlcDeviceDB plcdevicedb = plcdevicedbServiceImpl.getById(Integer.parseInt(item));
                    if (plcdevicedb.getDeviceType() == PlcDeviceType.CHAIN_STATION.getTypeNum()
                            || plcdevicedb.getDeviceType() == PlcDeviceType.TRANS_PLANTER.getTypeNum()
                            || plcdevicedb.getDeviceType() == PlcDeviceType.MONOMER_CONVEYOR.getTypeNum()
                            || plcdevicedb.getDeviceType() == PlcDeviceType.FOLDING_MACHINE.getTypeNum()
                    ) {
                        progressList.add(new BaseEum(plcdevicedb.getDeviceId(), plcdevicedb.getDeviceName()));
                    }
                }
            }
        }
        progressList.add(new BaseEum(TaskPlcProgress.ALL_DEVICE_COMPLETE.getProgressNum(), "所有设备任务完成（除小车）"));
        return ResponseData.success(progressList);
    }

    @GetMapping(value = "/queryTaskType")
    @ApiOperation("任务类型")
    public ResponseData queryTaskType() {
        return ResponseData.success("查询完成", taskDBService.queryTaskType());
    }

    @GetMapping(value = "/queryTaskProess")
    @ApiOperation("PLC任务进度")
    public ResponseData queryTaskProgress() {
        List<BaseEum> taskManagerProgress = taskDBService.queryTaskProgress();
        if (taskManagerProgress.size() > 0 && taskManagerProgress != null) {
            return ResponseData.success("查询完成", taskManagerProgress);
        } else {
            return ResponseData.error("此任务类型没有信息");
        }
    }

    @GetMapping(value = "/queryTaskRgvProess")
    @ApiOperation("小车任务进度")
    public ResponseData queryTaskRgvProgress() {
        List<BaseEum> taskManagerRgvProgress = taskDBService.queryTaskRgvProgress();
        if (taskManagerRgvProgress.size() > 0 && taskManagerRgvProgress != null) {
            return ResponseData.success("查询完成", taskManagerRgvProgress);
        } else {
            return ResponseData.error("此任务类型没有信息");
        }
    }

    @GetMapping(value = "/queryTaskStatus")
    @ApiOperation("小车任务状态")
    public ResponseData queryTaskRgvStatus() {
        List<BaseEum> taskManagerRgvProgress = taskDBService.queryTaskStatus();
        if (taskManagerRgvProgress.size() > 0 && taskManagerRgvProgress != null) {
            return ResponseData.success("查询完成", taskManagerRgvProgress);
        } else {
            return ResponseData.error("此任务类型没有信息");
        }
    }


    @PreAuthorize("@ss.hasPermi('taskdb:query')")
    @GetMapping(value = "/queryTaskStatusGroup")
    @ApiOperation("任务完成下拉选项")
    public ResponseData queryTaskStatusGroup() {
        List<BaseEum> baseEnums = taskDBService.queryTaskStatusGroup();
        if (baseEnums.size() > 0 && baseEnums != null) {
            return ResponseData.success("查询完成", baseEnums);
        } else {
            return ResponseData.error("此任务类型没有信息");
        }
    }

    @PreAuthorize("@ss.hasPermi('taskdb:query')")
    @GetMapping(value = "/queryRgvCar")
    @ApiOperation("获取在线小车信息")
    public ResponseData getAllRgv() {

        List<Rgv> carlist = SystemInit.RGVS;
        if (carlist.size() > 0) {
            return ResponseData.success("查询成功", SystemInit.RGVS);
        } else {
            return ResponseData.error("当前无小车信息");
        }
    }

    @Log(title = "任务管理", method = "任务恢复", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/recoverTask/{id}")
    @ApiOperation("任务恢复")
    public ResponseData recoverTask(@PathVariable("id") Integer id) {
        if (id == null || id < 1) {
            return ResponseData.error("任务不存在");
        }
        TaskDB taskdb = taskDBService.queryTaskInfoById(id);
        if (taskdb.getProcessingRgvNo() != null) {
            Rgv rgv = SystemInit.getByRgvNoTask(taskdb.getProcessingRgvNo());
            if (rgv != null) {
                if (RgvStatus.OFF_LINE == rgv.getRgvStatus()) {
                    return ResponseData.error("设置小车已离线");
                }
                if (RgvStatus.ERROR == rgv.getRgvStatus()) {
                    return ResponseData.error("设置小车已故障");
                }
                if (rgv.getCurLocation() == null) {
                    return ResponseData.error("请设置小车位置");
                }
            } else {
                return ResponseData.error("该小车已不存在");
            }
        }
        if (taskdb.getTaskStatus() != null && taskdb.getTaskStatus().getProgressNum() >= TaskStatus.FINISH.getProgressNum() &&
                !(taskdb.getTaskStatus().getProgressNum() == TaskStatus.ERROR.getProgressNum() || taskdb.getTaskStatus().getProgressNum() == TaskStatus.CANCEL.getProgressNum())) {
            return ResponseData.error("非错误和取消的任务无法恢复");
        }
        taskDBService.updateTaskStatus(taskdb, TaskStatus.WAIT);
        return ResponseData.success("恢复完成");
    }

    @Log(title = "任务管理", method = "PLC恢复功能", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/recoverPlcTask/{id}")
    @ApiOperation("PLC恢复功能")
    public ResponseData recoverPlcTask(@PathVariable("id") Integer id) {
        if (id == null || id < 1) {
            return ResponseData.error("任务不存在");
        }

        TaskDB taskdb = taskDBService.queryTaskInfoById(id);

        if (taskdb.getTaskType() == TaskType.OUT && taskdb.getRgvProgress() != TaskRgvProgress.RGV_COMPLETE) {
            return ResponseData.error("出库任务，小车任务状态为完成，不能执行plc任务");
        }

        log.info("手动恢复plc阶段任务执行");
        if (!taskdb.getPlcProgress().equals(TaskPlcProgress.ALL_DEVICE_COMPLETE.getProgressNum())) {
            if (!taskdb.getPlcProgress().equals(TaskPlcProgress.WAIT.getProgressNum())) {
                PlcDeviceDB plcDevById = plcdevicedbServiceImpl.queryPlcdevByDeviceId(taskdb.getPlcProgress());
                if (plcDevById == null) {
                    PlcDeviceProcess deviceProcess = PlcDeviceProcess.parseDeviceProcess(taskdb.getPlcProgress());
                    if (deviceProcess != PlcDeviceProcess.INVALID) {
                        String cacheKey = String.valueOf(taskdb.getTaskId());
                        String value = Plc.PLC_INTERRUPT_CACHE.get(cacheKey);
                        if (StringUtils.isEmpty(value)) {
                            log.info(cacheKey + "PLC恢复成功", cacheKey);
                            PlcTaskThread.getInstance(taskdb);
                            return ResponseData.success("恢复完成");
                        } else {
                            return ResponseData.error("执行中的任务，无法恢复！");
                        }
                    } else {
                        return ResponseData.error("Plc设备不存在");
                    }
                }
                log.info("plc阶段任务恢复开始执行的开始位置为：" + plcDevById.getDeviceName());
                if (plcDevById.getDeviceType().equals(PlcDeviceType.CHAIN_STATION.getTypeNum())) {
                    StationOper stationOper = (StationOper) Plc.deviceBaseNameMap.get(plcDevById.getDeviceName());
                    if (stationOper.getPalletNo().equals(taskdb.getPlcId()) || stationOper.getPalletNo() == 0) {
                        String cacheKey = String.valueOf(taskdb.getTaskId());
                        String value = Plc.PLC_INTERRUPT_CACHE.get(cacheKey);
                        if (StringUtils.isEmpty(value)) {
                            Plc.PLC_INTERRUPT_CACHE.put(String.valueOf(taskdb.getTaskId()), String.valueOf(taskdb.getTaskId()));
                            PlcDeviceDB plcDeviceDB = plcDeviceDBService.queryPlcdevByDeviceId(taskdb.getPlcProgress());
                            String deviceLocation = plcDeviceDB.getDeviceLocation();
                            LifterOper lifterOper = PlcUnit.getAutomaticLifterOper(Node.parseGrid(deviceLocation));
                            if (lifterOper != null) {
                                TwoDirectionRgvLifterOper twoDirectionRgvLifterOper = (TwoDirectionRgvLifterOper) lifterOper;
                                if (twoDirectionRgvLifterOper.isHasTwoDirectionRgv() && !twoDirectionRgvLifterOper.isTwoDirectionRgvRuning() && twoDirectionRgvLifterOper.isTwoDirectionRgvArrive()) {
                                    LifterPathNode.taskAfter(taskdb);
                                } else {
                                    return ResponseData.error("请先手动将两向车,开到提升机内!");
                                }
                            }
                            log.info(cacheKey + "PLC恢复成功", cacheKey);
                            PlcTaskThread.getInstance(taskdb);
                        } else {
                            return ResponseData.error("执行中的任务，无法恢复！");
                        }
                    } else {
                        return ResponseData.error("当前任务与工位任务不匹配，无法恢复！");
                    }
                } else if (
                        plcDevById.getDeviceType().equals(PlcDeviceType.MONOMER_CONVEYOR.getTypeNum())
                        || plcDevById.getDeviceType().equals(PlcDeviceType.TRANS_PLANTER.getTypeNum())
                        || plcDevById.getDeviceType().equals(PlcDeviceType.FOLDING_MACHINE.getTypeNum())
                ) {
                    DeviceInterface device = (DeviceInterface) Plc.deviceBaseNameMap.get(plcDevById.getDeviceName());
                    if (device == null) {
                        return ResponseData.error(plcDevById.getDeviceName() + "离线！");
                    }
                    if (device.getTaskNo().equals(taskdb.getPlcId()) || device.getTaskNo() == 0) {
                        String cacheKey = String.valueOf(taskdb.getTaskId());
                        String value = Plc.PLC_INTERRUPT_CACHE.get(cacheKey);
                        if (StringUtils.isEmpty(value)) {
                            Plc.PLC_INTERRUPT_CACHE.put(String.valueOf(taskdb.getTaskId()), String.valueOf(taskdb.getTaskId()));
                            PlcDeviceDB plcDeviceDB = plcDeviceDBService.queryPlcdevByDeviceId(taskdb.getPlcProgress());
                            String deviceLocation = plcDeviceDB.getDeviceLocation();
                            LifterOper lifterOper = PlcUnit.getAutomaticLifterOper(Node.parseGrid(deviceLocation));
                            if (lifterOper != null) {
                                TwoDirectionRgvLifterOper twoDirectionRgvLifterOper = (TwoDirectionRgvLifterOper) lifterOper;
                                if (twoDirectionRgvLifterOper.isHasTwoDirectionRgv() && !twoDirectionRgvLifterOper.isTwoDirectionRgvRuning() && twoDirectionRgvLifterOper.isTwoDirectionRgvArrive()) {
                                    LifterPathNode.taskAfter(taskdb);
                                } else {
                                    return ResponseData.error("请先手动将两向车,开到提升机内!");
                                }
                            }
                            log.info(cacheKey + "PLC恢复成功", cacheKey);
                            PlcTaskThread.getInstance(taskdb);
                        } else {
                            return ResponseData.error("执行中的任务，无法恢复！");
                        }
                    } else {
                        return ResponseData.error("当前任务与工位任务不匹配，无法恢复！");
                    }
                } else if (plcDevById.getDeviceType() == PlcDeviceType.PANASONIC_LIFT.getTypeNum()
                        || plcDevById.getDeviceType() == PlcDeviceType.SIEMENS_HOIST.getTypeNum()
                        || plcDevById.getDeviceType() == PlcDeviceType.TAMAGAWA_LIFTER.getTypeNum()
                        || plcDevById.getDeviceType() == PlcDeviceType.AUTOMATIC_LIFTER.getTypeNum()) {
                    LifterOper lifterOper = (LifterOper) Plc.deviceBaseNameMap.get(plcDevById.getDeviceName());
                    if (lifterOper == null) {
                        return ResponseData.error(plcDevById.getDeviceName() + "离线！");
                    }
                    if (lifterOper.isReady()) {
                        String cacheKey = String.valueOf(taskdb.getTaskId());
                        String value = Plc.PLC_INTERRUPT_CACHE.get(cacheKey);
                        if (StringUtils.isEmpty(value)) {
                            Plc.PLC_INTERRUPT_CACHE.put(String.valueOf(taskdb.getTaskId()), String.valueOf(taskdb.getTaskId()));
                            log.info(cacheKey + "PLC恢复成功", cacheKey);
                            PlcTaskThread.getInstance(taskdb);
                        } else {
                            return ResponseData.error("执行中的任务，无法恢复！");
                        }
                    } else {
                        return ResponseData.error(lifterOper.getDeviceName() + "未就绪！");
                    }
                }
            } else {
                String cacheKey = String.valueOf(taskdb.getTaskId());
                if (Plc.PLC_INTERRUPT_CACHE.get(cacheKey) != null) {
                    return ResponseData.error("执行中的任务，无法恢复！");
                }
                PlcTaskThread.getInstance(taskdb);
            }
        } else {
            return ResponseData.error("已完成任务不需要恢复!");
        }
        return ResponseData.success("恢复完成");
    }


    @Log(title = "任务管理", method = "PLC中断功能", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/interruptPlcTask/{id}")
    @ApiOperation("PLC中断功能")
    public ResponseData interruptPlcTask(@PathVariable("id") Integer id) {
        if (id == null || id < 1) {
            return ResponseData.error("任务不存在");
        }
        TaskDB taskdb = taskDBService.queryTaskInfoById(id);
        log.info("手动中断plc阶段任务执行");
        if (!taskdb.getPlcProgress().equals(TaskPlcProgress.ALL_DEVICE_COMPLETE.getProgressNum())) {
            String value = Plc.PLC_INTERRUPT_CACHE.get(String.valueOf(taskdb.getTaskId()));
            if (!StringUtils.isEmpty(value)) {
                Plc.PLC_INTERRUPT_CACHE.remove(String.valueOf(taskdb.getTaskId()));
            } else {
                return ResponseData.success("不需要中断！");
            }
        } else {
            return ResponseData.error("任务PLC阶段已完成");
        }
        TaskDetailDB taskDetailDB = taskDetailService.getTaskDetail(taskdb.getTaskId(), DetailProcess.HOIST_TASK, null, null, null, PrecessStatus.CONDUCT, null, null);
        TaskDetailDB detailDB;
        if (taskDetailDB != null) {
            if (PrecessStatus.COMPLETE.getValue().equals(taskDetailDB.getStatus())) {
                taskDetailDB = taskDetailService.getTaskDetail(taskdb.getTaskId(), DetailProcess.STATION_TASK, null, null, null, PrecessStatus.CONDUCT, null, null);
                detailDB = taskDetailService.buildTask(taskdb.getTaskId(), DetailProcess.HAND_INTERRUPT_PLC, taskDetailDB.getUuid(), null, null, PrecessStatus.CONDUCT, null, null);
                taskDetailService.updateTaskDetailCompleteTime(detailDB);
            } else {
                detailDB = taskDetailService.buildTask(taskdb.getTaskId(), DetailProcess.HAND_INTERRUPT_PLC, taskDetailDB.getUuid(), null, null, PrecessStatus.CONDUCT, null, null);
                taskDetailService.updateTaskDetailCompleteTime(detailDB);
            }
        } else {
            taskDetailDB = taskDetailService.getTaskDetail(taskdb.getTaskId(), DetailProcess.STATION_TASK, null, null, null, PrecessStatus.CONDUCT, null, null);
            detailDB = taskDetailService.buildTask(taskdb.getTaskId(), DetailProcess.HAND_INTERRUPT_PLC, taskDetailDB.getUuid(), null, null, PrecessStatus.CONDUCT, null, null);
            taskDetailService.updateTaskDetailCompleteTime(detailDB);
        }
        return ResponseData.success("PLC中断完成");
    }

    @PreAuthorize("@ss.hasPermi('taskdb:submitTask')")
    @Log(title = "任务管理", method = "提交WMS", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/submitTask/{id}")
    @ApiOperation("提交WMS")
    public ResponseData submitTask(@PathVariable("id") Integer id) {
        if (id == null || id < 1) {
            return ResponseData.error("任务不存在");
        }
        TaskDB taskdb = taskDBService.queryTaskInfoById(id);
        if (taskdb != null && taskdb.getRgvProgress() == TaskRgvProgress.RGV_COMPLETE) {
            if (StringUtils.isEmpty(taskdb.getWmsTaskId())) {
                return ResponseData.error("非WMS任务不用上报");
            } else if (taskdb.getCommitTime() != null) {
                return ResponseData.error("已上报，不可重复上报");
            } else {
                NodeDB nodeDBEnd = nodeDBService.getNodeDB(Node.parseGrid(taskdb.getEndNodeStr()));
                toWms.executionPhase(TaskStatusRtn.buildTaskStatusRtn(taskdb.getWmsTaskId(),nodeDBEnd.getGridId(),  WmsTaskStatus.FINISH));
                if (taskdb.getProcessingRgvNo() != null) {
                    Rgv rgv = SystemInit.getByRgvNo(taskdb.getProcessingRgvNo());
                    // 如果是5代车且是出入移，则更新小车身上无货
                    if (rgv != null && rgv.checkRgvType(RgvType.FIVE_POINT_FOUR_TL)
                            && taskdb.getTaskId().equals(rgv.getCargoTaskId())
                            && (TaskType.IN.equals(taskdb.getTaskType())
                            || TaskType.OUT.equals(taskdb.getTaskType())
                            || TaskType.TRANSFER.equals(taskdb.getTaskType()))) {
                        rgv.setCargoTaskId(null);
                    }
                }
                return ResponseData.success("提交任务已创建！");
            }
        } else {
            return ResponseData.error("未完成任务不能提交");
        }
    }

    @PreAuthorize("@ss.hasPermi('taskdb:remove')")
    @Log(title = "任务管理", method = "根据勾选删除任务", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/deleteTask/{ids}")
    @ApiOperation("根据勾选删除任务")
    public ResponseData deleteTask(@PathVariable List<Integer> ids) {
        if (ids == null || ids.size() == 0) {
            return ResponseData.error("请勾选删除项");
        } else {
            List<TaskDB> taskDBS = new ArrayList<>();
            for (Integer id : ids) {
                TaskDB taskdb = taskDBService.queryTaskInfoById(id);
                if (taskdb != null && taskdb.getTaskStatus() != TaskStatus.FINISH
                        && taskdb.getTaskStatus() != TaskStatus.COMMITTED
                        && taskdb.getTaskStatus() != TaskStatus.CANCEL) {
                    return ResponseData.error(taskdb.getTaskId() + "任务当前未完成不可删除");
                }
                taskDBS.add(taskdb);
            }
            int success = taskDBService.deleteTask(taskDBS);
            if (success > 0) {
                return ResponseData.success("任务删除完成");
            } else {
                return ResponseData.error("所选任务号不存在");
            }
        }
    }

    @PreAuthorize("@ss.hasPermi('taskdb:export')")
    @Log(title = "任务管理", method = "导出任务列表", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ApiOperation("导出任务列表")
    public ResponseData export(TaskDB taskDB) {
        List<TaskDB> list = taskDBService.queryTasks(taskDB);
        ExcelUtil<TaskDB> util = new ExcelUtil<TaskDB>(TaskDB.class);
        return util.exportExcel(list, "任务列表");
    }

    @Log(title = "任务管理", method = "取消任务", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/disableTask/{id}")
    @ApiOperation("取消任务")
    public ResponseData disableTask(@PathVariable("id") Integer id) {
        log.info("接收到任务取消命令");
        if (id == null || id < 1) {
            return ResponseData.error("任务不存在");
        }
        TaskDB taskdb = taskDBService.queryTaskInfoById(id);
        if (taskdb.getTaskStatus().getProgressNum() > TaskStatus.WAIT.getProgressNum()) {
            return ResponseData.error("非新生成和等待执行中的任务，不可取消");
        }
        if (taskdb.getProcessingRgvNo() != null) {
            Rgv rgv = SystemInit.getByRgvNo(taskdb.getProcessingRgvNo());
            // 如果是5代车且是出入移，则更新小车身上无货
            if (rgv != null && rgv.checkRgvType(RgvType.FIVE_POINT_FOUR_TL)
                    && taskdb.getTaskId().equals(rgv.getCargoTaskId())
                    && (TaskType.IN.equals(taskdb.getTaskType())
                    || TaskType.OUT.equals(taskdb.getTaskType())
                    || TaskType.TRANSFER.equals(taskdb.getTaskType()))) {
                rgv.setCargoTaskId(null);
            }
        }
        taskDBService.updateTaskStatus(taskdb, TaskStatus.CANCEL);
        String value = Plc.PLC_INTERRUPT_CACHE.get(String.valueOf(taskdb.getTaskId()));
        if (!StringUtils.isEmpty(value)) {
            Plc.PLC_INTERRUPT_CACHE.remove(String.valueOf(taskdb.getTaskId()));
        }
        return ResponseData.success("任务已取消");
    }

    @Log(title = "任务管理", method = "强制取消任务", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/forceDisableTask/{id}")
    @ApiOperation("强制取消任务")
    public ResponseData forceDisableTask(@PathVariable("id") Integer id) {
        if (id == null || id < 1) {
            return ResponseData.error("任务不存在");
        }
        TaskDB taskdb = taskDBService.queryTaskInfoById(id);
        taskDBService.updateTaskStatus(taskdb, TaskStatus.CANCEL);
        String value = Plc.PLC_INTERRUPT_CACHE.get(String.valueOf(taskdb.getTaskId()));
        if (!StringUtils.isEmpty(value)) {
            Plc.PLC_INTERRUPT_CACHE.remove(String.valueOf(taskdb.getTaskId()));
        }
        Rgv assignedRgv = taskdb.selectProcessingRgvPojo();
        if (assignedRgv != null && assignedRgv.getCurTask() != null
                && assignedRgv.getCurTask().getTaskId().intValue() == id.intValue()) {
            assignedRgv.getCurTask().setTaskStatus(TaskStatus.CANCEL);
        }
        return ResponseData.success("任务已取消");
    }

    @Log(title = "任务管理", method = "手动分车", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/assignTaskToRgv/{id}")
    @ApiOperation("手动分车")
    public ResponseData assignTaskToRgv(@PathVariable("id") Integer id) {
        if (id == null || id < 1) {
            return ResponseData.error("任务不存在");
        }
        TaskDB taskdb = taskDBService.queryTaskInfoById(id);
        if (taskdb.getTaskStatus().getProgressNum() > TaskStatus.WAIT.getProgressNum()) {
            return ResponseData.error("非新生成和等待执行中的任务，不可分车");
        }
        Rgv rgv = rgvTaskAssign.bindNewAvailableRgvWithTask(taskdb);
        if (rgv == null) {
            return ResponseData.error("没有可分配的车辆");
        }
        return ResponseData.success("任务重新分配完成");
    }

    @PreAuthorize("@ss.hasPermi('taskdb:edit')")
    @Log(title = "任务管理", method = "修改任务信息", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/changeTaskInfo/{id}")
    @ApiOperation("修改任务信息")
    public ResponseData changeTaskInfo(@PathVariable("id") Integer id, @RequestBody ChangeTaskInfoRequest request) {
        if (id == null || id < 1) {
            return ResponseData.error("任务不存在");
        }
        if (request != null && request.checkHasEmpty()) {
            return ResponseData.error("请求参数有误");
        }
        TaskDB taskdb = taskDBService.queryTaskInfoById(id);
        if (taskdb == null) {
            return ResponseData.error("任务Id不存在");
        }

        if (request.getPriorityCode() >= 10000) {
            if (!taskdb.getPriorityCode().equals(request.getPriorityCode())) {
                return ResponseData.error("任务优先级修改值必须在0-9999之间");
            }
        }

        if (TaskStatus.FINISH.getProgressNum() == request.getTaskStatus().intValue()) {
            if (request.getRgvProgress().intValue() != TaskRgvProgress.RGV_COMPLETE.getProgressNum() ||
                    request.getPlcProgress().intValue() != TaskPlcProgress.ALL_DEVICE_COMPLETE.getProgressNum()) {
                return ResponseData.error("任务状态无法修改为完成。需要Plc状态和小车状态均完成");
            }
        }
        if (TaskStatus.COMMITTED.getProgressNum() == request.getTaskStatus().intValue() && taskdb.getTaskType().equals(TaskType.CHARGE)) {
            return ResponseData.error("充电任务状态无法修改为提交WMS");
        }
        if (request.getPlcProgress().intValue() != TaskPlcProgress.ALL_DEVICE_COMPLETE.getProgressNum()) {
            // 把PLC中断掉
            String value = Plc.PLC_INTERRUPT_CACHE.get(String.valueOf(taskdb.getTaskId()));
            if (StringUtils.isEmpty(value)) {
                Plc.PLC_INTERRUPT_CACHE.put(String.valueOf(taskdb.getTaskId()), String.valueOf(taskdb.getTaskId()));
            }
            //TODO 并且如果该任务占用提升机也把提升机解锁掉

        }
        Integer taskRgvProgressProgressNum = request.getRgvProgress();
        if (taskdb.getProcessingRgvNo() == null && request.getProcessingRgvNo() != null) {
            if (request.getRgvProgress().intValue() > TaskRgvProgress.ASSIGNED_TO_RGV.getProgressNum()) {
                return ResponseData.error("任务无法修改执行车辆。小车任务进度为等待分配车辆、预分车、已分配车辆才可以修改执行车辆");
            }
            if (request.getTaskStatus().intValue() != TaskStatus.WAIT.getProgressNum()) {
                return ResponseData.error("任务无法修改执行车辆。任务状态为等待执行中才可以修改执行车辆");
            }
            taskRgvProgressProgressNum = TaskRgvProgress.ASSIGNED_TO_RGV.getProgressNum();
        }
        if (taskdb.getProcessingRgvNo() != null && request.getProcessingRgvNo() == null) {
            if (request.getRgvProgress().intValue() > TaskRgvProgress.ASSIGNED_TO_RGV.getProgressNum()) {
                return ResponseData.error("任务无法修改执行车辆。小车任务进度为等待分配车辆、预分车、已分配车辆才可以修改执行车辆");
            }
            if (request.getTaskStatus().intValue() != TaskStatus.WAIT.getProgressNum()) {
                return ResponseData.error("任务无法修改执行车辆。任务状态为等待执行中才可以修改执行车辆");
            }
            if (taskdb.getPreProcessingRgvNo() != null) {
                taskRgvProgressProgressNum = TaskRgvProgress.PREASSIGN.getProgressNum();
            } else {
                taskRgvProgressProgressNum = TaskRgvProgress.NOT_ASSIGNED_TO_RGV.getProgressNum();
            }
        }
        if (taskdb.getProcessingRgvNo() != null && request.getProcessingRgvNo() != null && !taskdb.getProcessingRgvNo().equals(request.getProcessingRgvNo())) {
            if (request.getRgvProgress().intValue() > TaskRgvProgress.ASSIGNED_TO_RGV.getProgressNum()) {
                return ResponseData.error("任务无法修改执行车辆。小车任务进度为等待分配车辆、预分车、已分配车辆才可以修改执行车辆");
            }
            if (request.getTaskStatus().intValue() != TaskStatus.WAIT.getProgressNum()) {
                return ResponseData.error("任务无法修改执行车辆。任务状态为等待执行中才可以修改执行车辆");
            }
            taskRgvProgressProgressNum = TaskRgvProgress.ASSIGNED_TO_RGV.getProgressNum();
        }
        if (taskdb.getPriorityCode() == null && request.getPriorityCode() != null) {
            if (request.getTaskStatus().intValue() != TaskStatus.WAIT.getProgressNum()) {
                return ResponseData.error("任务无法修改优先级。任务状态为等待执行中才可以修改优先级");
            }
        }
        if (taskdb.getPriorityCode() != null && request.getPriorityCode() == null) {
            if (request.getTaskStatus().intValue() != TaskStatus.WAIT.getProgressNum()) {
                return ResponseData.error("任务无法修改优先级。任务状态为等待执行中才可以修改优先级");
            }
        }
        if (taskdb.getPriorityCode() != null && request.getPriorityCode() != null && !taskdb.getPriorityCode().equals(request.getPriorityCode())) {
            if (request.getTaskStatus().intValue() != TaskStatus.WAIT.getProgressNum()) {
                return ResponseData.error("任务无法修改优先级。任务状态为等待执行中才可以修改优先级");
            }
        }
        taskdb.setTaskStatus(TaskStatus.getByTaskProgress(request.getTaskStatus().intValue()));
        taskdb.setRgvProgress(TaskRgvProgress.getByTaskProgress(taskRgvProgressProgressNum));
        PlcDeviceDB plcdevicedb = plcdevicedbServiceImpl.getPlcDevById(request.getPlcProgress());
        if (plcdevicedb != null || request.getPlcProgress() == TaskPlcProgress.ALL_DEVICE_COMPLETE.getProgressNum()
                || request.getPlcProgress() == TaskPlcProgress.WAIT.getProgressNum()) {
            taskdb.setPlcProgress(request.getPlcProgress());
        } else {
            return ResponseData.error("Plc设备不存在");
        }
        taskdb.setPlcProgress(request.getPlcProgress().intValue());
        taskdb.setProcessingRgvNo(request.getProcessingRgvNo());
        taskdb.setPriorityCode(request.getPriorityCode());
        if (request.getTaskStatus().intValue() != TaskStatus.COMMITTED.getProgressNum()) {
            taskdb.setCommitTime(null);
        }
        if (taskdb.getTaskStatus() == TaskStatus.FINISH
                && taskdb.getPlcProgress().equals(TaskPlcProgress.ALL_DEVICE_COMPLETE.getProgressNum())
                && taskdb.getRgvProgress() == TaskRgvProgress.RGV_COMPLETE
        ) {
            //任务状态是完成、plc进度是完成且小车状态是完成，自动上报wms
            taskdb.setRemark("500");
        }
        int success = taskDBService.updateTaskInfoAllowNull(taskdb);
        if (success == 1) {
            if (TaskStatus.FINISH.getProgressNum() == request.getTaskStatus().intValue()) {
                // 当前任务有后置任务，把当前任务的后置任务设置为可预分车
                TaskDB sufTask = taskDBService.findTaskByPreTaskId(id);
                if (sufTask != null) {
                    taskDBService.updateIsAllowAssignmentRgv(sufTask, true);
                }
                String value = Plc.PLC_INTERRUPT_CACHE.get(String.valueOf(taskdb.getTaskId()));
                if (!StringUtils.isEmpty(value)) {
                    Plc.PLC_INTERRUPT_CACHE.remove(String.valueOf(taskdb.getTaskId()));
                }
            } else if (TaskStatus.CANCEL.getProgressNum() == request.getTaskStatus().intValue()) {
                String value = Plc.PLC_INTERRUPT_CACHE.get(String.valueOf(taskdb.getTaskId()));
                if (!StringUtils.isEmpty(value)) {
                    Plc.PLC_INTERRUPT_CACHE.remove(String.valueOf(taskdb.getTaskId()));
                }
            }
            if (taskdb.getProcessingRgvNo() != null
                    && (request.getTaskStatus().intValue() == TaskStatus.FINISH.getProgressNum()
                    || request.getTaskStatus().intValue() == TaskStatus.COMMITTED.getProgressNum()
                    || request.getTaskStatus().intValue() == TaskStatus.CANCEL.getProgressNum())) {
                Rgv rgv = SystemInit.getByRgvNo(taskdb.getProcessingRgvNo());
                // 如果是5代车且是出入移，则更新小车身上无货
                if (rgv != null && rgv.checkRgvType(RgvType.FIVE_POINT_FOUR_TL)
                        && taskdb.getTaskId().equals(rgv.getCargoTaskId())
                        && (TaskType.IN.equals(taskdb.getTaskType())
                        || TaskType.OUT.equals(taskdb.getTaskType())
                        || TaskType.TRANSFER.equals(taskdb.getTaskType()))) {
                    rgv.setCargoTaskId(null);
                }
            }
            return ResponseData.success("任务修改成功");
        } else {
            return ResponseData.error("任务修改失败");
        }
    }

    /**
     * Nodedb 转换成Node
     *
     * @param Nodedb
     * @return
     */
    public static Node parseNodedb(NodeDB Nodedb) {
        if (Nodedb == null) {
            return null;
        }
        int x = Nodedb.getGridx();
        int y = Nodedb.getGridy();
        int z = Nodedb.getGridz();
        return new Node(x, y, z);
    }

    /**
     * 判断任务列表中是不是有指定任务
     */
    public static Boolean contains(Queue<TaskDB> taskDBS, TaskDB taskdb) {
        for (TaskDB taskDB1 : taskDBS) {
            if (taskDB1.equals(taskdb)) {
                return true;
            }
        }
        return false;
    }


    @PreAuthorize("@ss.hasPermi('taskdb:generate')")
    @Log(title = "任务管理", method = "小车动作循环测试", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/actionCycleTask")
    @ResponseBody
    @ApiOperation(value = "小车动作循环测试")
    public ResponseData actionCycleTask(@RequestBody ActionTaskRequest actionTaskRequest) {
        try {
            LoggerUtil.info("小车动作循环测试:" + actionTaskRequest, this.getClass());
            if (actionTaskRequest.getRgvNo() == null) {
                return ResponseData.error("小车编号不能为空");
            }

            if (actionTaskRequest.getActionType() == null) {
                return ResponseData.error("任务类型不能为空");
            }

            ActionTestType action = ActionTestType.parseAction(actionTaskRequest.getActionType());

            if (action == null) {
                return ResponseData.error("任务类型错误:" + actionTaskRequest.getActionType());
            }

            Rgv rgv = SystemInit.getByRgvNo(actionTaskRequest.getRgvNo());

            if (rgv == null) {
                return ResponseData.error("未找到对应的小车:" + actionTaskRequest.getRgvNo());
            }

            if (rgv.getRgvStatus() != RgvStatus.READY) {
                return ResponseData.error("小车未就绪，无法执行任务");
            }

            if (rgv.getCurLocation() == null) {
                return ResponseData.error("请同步小车位置");
            }

            ActionCycleTask.analyzeAction(rgv, action);

            return ResponseData.success();
        } catch (Exception e) {
            WcsUtil.exceptionLog(e, this.getClass());
            return ResponseData.error(e.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('taskdb:generate')")
    @Log(title = "任务管理", method = "任务循环测试", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/generateCycleTask")
    @ResponseBody
    @ApiOperation(value = "任务循环测试")
    public ResponseData generateCycleTask(@RequestBody CycleTaskGenerateRequest taskGenerate) {
        try {
            LoggerUtil.info("任务循环测试:" + taskGenerate, this.getClass());
            if (taskGenerate.getRgvNo() == null) {
                return ResponseData.error("小车编号不能为空");
            }

            if (taskGenerate.getTaskType() == null) {
                return ResponseData.error("任务类型不能为空");
            }

            if (taskGenerate.getEndNode() == null) {
                return ResponseData.error("任务终点不能为空");
            }

            TaskType taskType = TaskType.parseTaskType(taskGenerate.getTaskType());

            Rgv rgv = SystemInit.getByRgvNo(taskGenerate.getRgvNo());

            if (rgv == null) {
                return ResponseData.error("未找到对应的小车:" + taskGenerate.getRgvNo());
            }

            if (!TaskCycleAction.isRgvHasTask(rgv) && rgv.getRgvStatus() != RgvStatus.READY) {
                return ResponseData.error("小车未就绪，无法执行任务");
            }

            if (rgv.getCurLocation() == null) {
                return ResponseData.error("请同步小车位置");
            }

            NodeDB nodeDB = nodeDBService.getById(taskGenerate.getEndNode());

            Node node = new Node(nodeDB.getGridx(), nodeDB.getGridy(), nodeDB.getGridz());
            if (rgv.getCurLocation().equals(node)) {
                return ResponseData.error("任务终点不能选小车当前点");
            }
            if (nodeDB.getGridType().equals(NodeType.B)) {
                return ResponseData.error("任务终点不能选禁用点");
            }
            if (nodeDB.getGridType().equals(NodeType.ST)) {
                return ResponseData.error("任务终点不能选工位");
            }
            TaskCycleAction.analyzeTask(rgv, taskType, new Node(nodeDB.getGridx(), nodeDB.getGridy(), nodeDB.getGridz()));

            return ResponseData.success();
        } catch (Exception e) {
            WcsUtil.exceptionLog(e, this.getClass());
            return ResponseData.error(e.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('taskdb:generate')")
    @Log(title = "任务管理", method = "地码检测任务", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/checkCodeTask")
    @ResponseBody
    @ApiOperation(value = "地码检测任务")
    public ResponseData checkCodeTask(@RequestBody TaskGenerateRequest taskGenerate) {
        try {
            LoggerUtil.info("地码检测任务:" + taskGenerate, this.getClass());
            if (taskGenerate == null) {
                return ResponseData.error("任务不能为空");
            }
            if (taskGenerate.getTaskType() == null) {
                return ResponseData.error("任务类型不能为空");
            }
            if (taskGenerate.getTaskType() == TaskType.CHECK_GCODE.getTypeNum() && StringUtils.isEmpty(taskGenerate.getEndNodeStr())) {
                return ResponseData.error("地码检测任务，请选择终点");
            }
            if (taskGenerate.getTaskType() == TaskType.CHECK_GCODE.getTypeNum() && taskGenerate.getRgvNo() == null) {
                return ResponseData.error("该任务类型不支持系统分配执行车辆！请手动分配小车");
            }
            Rgv rgv = null;
            if (!taskGenerate.isSystemAssignedMode()) {
                if (taskGenerate.getRgvNo() == null) {
                    return ResponseData.error("该任务类型不支持系统分配执行车辆！请手动分配小车");
                }
                rgv = SystemInit.getByRgvNo(taskGenerate.getRgvNo());

                if (RgvStatus.OFF_LINE == rgv.getRgvStatus()) {
                    return ResponseData.error("设置小车已离线");
                }
                if (rgv.getCurLocation() == null) {
                    return ResponseData.error("请设置小车位置");
                }
                if (!rgv.checkRgvType(RgvType.RGV_FORK)) {
                    if (PalletStatus.UP == rgv.getPalletStatus()) {
                        return ResponseData.error("当前任务不可在托板顶升时执行，请确认小车托板是否顶升");
                    }
                }
            }
            Node endNode = parseNodedb(getRgvEndNode(taskGenerate));
            NodeDB rgvEndSNode = getRgvEndNode(taskGenerate);
            if (rgvEndSNode != null && rgvEndSNode.getGridType().getCode().equals(NodeType.B.getCode())) {
                return ResponseData.error("终点位置禁用，不能生成任务");
            }
            if (rgvEndSNode != null && !rgvEndSNode.getCanToStop()) {
                return ResponseData.error("终点位置不可停留，不能生成任务");
            }
            RgvCheckMap.checkMap(rgv, endNode);
            return ResponseData.success();
        } catch (Exception e) {
            WcsUtil.exceptionLog(e, this.getClass());
            return ResponseData.error(e.getMessage());
        }
    }

    @PreAuthorize("@ss.hasPermi('taskdb:generate')")
    @Log(title = "任务管理", method = "子车空载行驶", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/sonUnLoadTask")
    @ResponseBody
    @ApiOperation(value = "子车空载行驶")
    public ResponseData sonUnloadTask(@RequestBody CycleTaskGenerateRequest taskGenerate) {
        try {
            LoggerUtil.info("子车空载行驶:" + taskGenerate, this.getClass());
            if (taskGenerate.getRgvNo() == null) {
                return ResponseData.error("小车编号不能为空");
            }
            if (taskGenerate.getEndNode() == null) {
                return ResponseData.error("任务终点不能为空");
            }
            Rgv rgv = SystemInit.getByRgvNo(taskGenerate.getRgvNo());

            if (rgv == null) {
                return ResponseData.error("未找到对应的小车:" + taskGenerate.getRgvNo());
            }
            if (!TaskCycleAction.isRgvHasTask(rgv) && rgv.getRgvStatus() == RgvStatus.OFF_LINE) {
                return ResponseData.error("小车离线，无法执行任务");
            }
//            if (rgv.getCurLocation() == null) {
//                return ResponseData.error("请确认小车位置");
//            }
            if (!rgv.checkRgvType(RgvType.RGV_SON_MOTHER)) {
                return ResponseData.error("设备号为 " + taskGenerate.getRgvNo() + " 的小车 不是子母车");
            }
            NodeDB nodeDB = nodeDBService.getById(taskGenerate.getEndNode());
            Node node = new Node(nodeDB.getGridx(), nodeDB.getGridy(), nodeDB.getGridz());
//            if (rgv.getCurLocation().equals(node)) {
//                return ResponseData.error("任务终点不能选小车当前点");
//            }
            if (!nodeDB.getGridType().equals(NodeType.P) && !node.equals(rgv.getCurLocation())) {
                return ResponseData.error("任务终点必须是货位或则母车当前位置");
            }
            RgvSonNewTaskHandle.analyzeLineNodes(((RgvSM) rgv).getSonRgvLocation(), node);
            WcsUtil.generalTask(null, node, rgv, TaskType.RGV_SON_MOVE_UNLOADED,
                    taskDBService, this.getClass());
            return ResponseData.success();
        } catch (Exception e) {
            WcsFuncUtil.exceptionLog(e, this.getClass());
            return ResponseData.error(e.getMessage());
        }
    }

    /**
     * 查询图表数据
     *
     * @param taskDB
     * @return
     */
    @PreAuthorize("@ss.hasPermi('taskdb:query')")
    @ApiOperation(value = "查询图表数据")
    @PostMapping(value = "/getTaskData")
    @ResponseBody
    public ResponseData getTaskData(TaskDB taskDB) {
        try {
            Date sendTime = taskDB.getCreateTime();
            Date sendTimeStart;
            Date sendTimeEnd;
            if (sendTime == null) {
                sendTimeEnd = new Date();
            } else {
                sendTimeEnd = sendTime;
            }
            sendTimeStart = DateUtils.addDays(sendTimeEnd, -15);
            Map<String, Object> params = new HashMap<>();
            params.put("beginTime", sendTimeStart);
            params.put("endTime", sendTimeEnd);
            taskDB.setParams(params);
            List<Map<String, Object>> datalist = taskDBService.getGraphData(taskDB);
            return ResponseData.success("查询成功", datalist);
        } catch (Exception e) {
            return ResponseData.error(e.getMessage());
        }
    }
}
